package com.sdy.healthcode.h5.controller.user;

import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.DateUtil;
import com.sdy.healthcode.biz.dto.HealthClockInDTO;
import com.sdy.healthcode.biz.service.HealthClockInService;
import com.sdy.mvc.controller.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/healthClockIn")
@Api(tags = "用户健康打卡相关接口")
public class HealthClockInController extends BaseController {
    @Autowired
    private HealthClockInService healthClockInService;

    @GetMapping("/lastClockIn")
    @ApiOperation(value = "上次打卡数据")
    public Response lastClockIn(HttpServletRequest request) {
        Integer userId = getUserId(request);
        HealthClockInDTO healthClockIn = healthClockInService.getClockIn(DateUtil.getDateBegin(new Date()), userId);
        return Response.success(healthClockIn);
    }

    @PostMapping("/clockIn")
    @ApiOperation(value = "打卡")
    public Response healthClockIn(HttpServletRequest request, @RequestBody HealthClockInDTO healthClockIn) throws BizException, InterruptedException {
        Integer userId = getUserId(request);
        healthClockIn.setUserId(userId);
        healthClockInService.clockInLockable(healthClockIn);
        return Response.success();
    }
    
    @GetMapping("/get")
    @ApiOperation(value = "获取单条打卡数据")
    @ApiImplicitParam(value = "打卡日期", name = "date", defaultValue = "2020-02-23")
    public Response<HealthClockInDTO> get(HttpServletRequest request, String date) {
        Integer userId = getUserId(request);
        HealthClockInDTO clockIn = healthClockInService.getClockIn(DateUtil.getDate(date, DateUtil.DATE_FORMAT), userId);
        return Response.success(clockIn);
    }

    @GetMapping("/history")
    @ApiOperation(value = "获取打卡历史记录")
    public Response pageData(HttpServletRequest request) {
        List<Date> history = healthClockInService.clockInHistory(getUserId(request));
        return Response.success(history.stream().map(DateUtil::formatDate).collect(Collectors.toList()));
    }
}
